<template>
  <view class="meditation-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">冥想练习</text>
      </view>
    </view>

    <!-- 冥想课程列表 -->
    <view class="course-list">
      <view class="course-item" v-for="course in meditationCourses" :key="course.id" @tap="playCourse(course)">
        <view class="course-cover">
          <image class="cover-image" :src="course.cover" mode="aspectFill"></image>
          <view class="play-overlay">
            <text class="play-icon">▶️</text>
          </view>
        </view>
        
        <view class="course-info">
          <view class="course-header">
            <text class="course-title">{{ course.title }}</text>
            <view class="course-duration">
              <text class="duration-text">{{ course.duration }}</text>
            </view>
          </view>
          
          <text class="course-desc">{{ course.description }}</text>
          
          <view class="course-meta">
            <view class="meta-item">
              <text class="meta-icon">👥</text>
              <text class="meta-text">{{ course.participants }}人参与</text>
            </view>
            <view class="meta-item">
              <text class="meta-icon">⭐</text>
              <text class="meta-text">{{ course.rating }}</text>
            </view>
            <view class="meta-item">
              <text class="meta-icon">🎯</text>
              <text class="meta-text">{{ course.level }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 播放器 -->
    <view class="player-container" v-if="currentCourse">
      <view class="player-content">
        <view class="player-info">
          <image class="player-cover" :src="currentCourse.cover" mode="aspectFill"></image>
          <view class="player-text">
            <text class="player-title">{{ currentCourse.title }}</text>
            <text class="player-progress">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</text>
          </view>
        </view>
        
        <view class="player-controls">
          <text class="control-btn" @tap="previousTrack">⏮️</text>
          <text class="control-btn play-btn" @tap="togglePlay">{{ isPlaying ? '⏸️' : '▶️' }}</text>
          <text class="control-btn" @tap="nextTrack">⏭️</text>
        </view>
      </view>
      
      <view class="progress-bar">
        <view class="progress-track">
          <view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentCourse: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
      progressTimer: null,
      meditationCourses: [
        {
          id: 1,
          title: '初学者冥想指导',
          description: '适合冥想初学者的基础练习，帮助你建立正确的冥想习惯',
          cover: '/static/images/meditation1.jpg',
          duration: '10:00',
          participants: 1234,
          rating: 4.8,
          level: '初级',
          audioUrl: '/static/audio/meditation1.mp3'
        },
        {
          id: 2,
          title: '深度放松冥想',
          description: '通过深度呼吸和身体扫描，释放身心压力，获得深度放松',
          cover: '/static/images/meditation2.jpg',
          duration: '15:00',
          participants: 892,
          rating: 4.9,
          level: '中级',
          audioUrl: '/static/audio/meditation2.mp3'
        },
        {
          id: 3,
          title: '正念呼吸练习',
          description: '专注于呼吸的正念练习，提高专注力和觉察力',
          cover: '/static/images/meditation3.jpg',
          duration: '8:00',
          participants: 2156,
          rating: 4.7,
          level: '初级',
          audioUrl: '/static/audio/meditation3.mp3'
        },
        {
          id: 4,
          title: '睡前冥想',
          description: '温和的睡前冥想练习，帮助你放松身心，改善睡眠质量',
          cover: '/static/images/meditation4.jpg',
          duration: '20:00',
          participants: 1567,
          rating: 4.8,
          level: '初级',
          audioUrl: '/static/audio/meditation4.mp3'
        },
        {
          id: 5,
          title: '情绪平衡冥想',
          description: '通过冥想练习调节情绪，培养内心的平静与稳定',
          cover: '/static/images/meditation5.jpg',
          duration: '12:00',
          participants: 743,
          rating: 4.6,
          level: '中级',
          audioUrl: '/static/audio/meditation5.mp3'
        },
        {
          id: 6,
          title: '专注力提升冥想',
          description: '专门设计的专注力训练，提高工作和学习效率',
          cover: '/static/images/meditation6.jpg',
          duration: '18:00',
          participants: 1089,
          rating: 4.9,
          level: '高级',
          audioUrl: '/static/audio/meditation6.mp3'
        }
      ]
    }
  },
  
  computed: {
    progressPercent() {
      if (this.duration === 0) return 0
      return (this.currentTime / this.duration) * 100
    }
  },
  
  onUnload() {
    this.stopAudio()
  },
  
  methods: {
    goBack() {
      this.stopAudio()
      uni.navigateBack()
    },
    
    playCourse(course) {
      if (this.currentCourse && this.currentCourse.id === course.id) {
        this.togglePlay()
        return
      }
      
      this.stopAudio()
      this.currentCourse = course
      this.startAudio()
      
      // 记录播放历史
      this.recordPlayHistory(course)
    },
    
    startAudio() {
      // 模拟音频播放
      this.isPlaying = true
      this.currentTime = 0
      this.duration = this.parseDuration(this.currentCourse.duration)
      
      this.progressTimer = setInterval(() => {
        if (this.isPlaying && this.currentTime < this.duration) {
          this.currentTime += 1
        } else if (this.currentTime >= this.duration) {
          this.onAudioEnd()
        }
      }, 1000)
      
      uni.showToast({
        title: '开始播放',
        icon: 'success'
      })
    },
    
    stopAudio() {
      this.isPlaying = false
      if (this.progressTimer) {
        clearInterval(this.progressTimer)
        this.progressTimer = null
      }
    },
    
    togglePlay() {
      if (!this.currentCourse) return
      
      this.isPlaying = !this.isPlaying
      
      if (this.isPlaying && !this.progressTimer) {
        this.progressTimer = setInterval(() => {
          if (this.isPlaying && this.currentTime < this.duration) {
            this.currentTime += 1
          } else if (this.currentTime >= this.duration) {
            this.onAudioEnd()
          }
        }, 1000)
      }
    },
    
    previousTrack() {
      const currentIndex = this.meditationCourses.findIndex(course => course.id === this.currentCourse.id)
      const prevIndex = currentIndex > 0 ? currentIndex - 1 : this.meditationCourses.length - 1
      this.playCourse(this.meditationCourses[prevIndex])
    },
    
    nextTrack() {
      const currentIndex = this.meditationCourses.findIndex(course => course.id === this.currentCourse.id)
      const nextIndex = currentIndex < this.meditationCourses.length - 1 ? currentIndex + 1 : 0
      this.playCourse(this.meditationCourses[nextIndex])
    },
    
    onAudioEnd() {
      this.isPlaying = false
      this.currentTime = 0
      
      if (this.progressTimer) {
        clearInterval(this.progressTimer)
        this.progressTimer = null
      }
      
      uni.showToast({
        title: '播放完成',
        icon: 'success'
      })
      
      // 记录完成
      this.recordCompletion()
    },
    
    parseDuration(durationStr) {
      const [minutes, seconds] = durationStr.split(':').map(Number)
      return minutes * 60 + (seconds || 0)
    },
    
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    
    recordPlayHistory(course) {
      try {
        let history = uni.getStorageSync('course_history') || []
        
        // 移除重复记录
        history = history.filter(item => item.courseId !== course.id || item.type !== 'meditation')
        
        // 添加新记录
        history.unshift({
          courseId: course.id,
          type: 'meditation',
          title: course.title,
          cover: course.cover,
          duration: course.duration,
          playTime: new Date().toISOString()
        })
        
        // 只保留最近50条记录
        if (history.length > 50) {
          history = history.slice(0, 50)
        }
        
        uni.setStorageSync('course_history', history)
      } catch (e) {
        console.error('记录播放历史失败:', e)
      }
    },
    
    recordCompletion() {
      try {
        let completions = uni.getStorageSync('course_completions') || []
        
        const completion = {
          courseId: this.currentCourse.id,
          type: 'meditation',
          title: this.currentCourse.title,
          completedAt: new Date().toISOString(),
          duration: this.currentCourse.duration
        }
        
        completions.unshift(completion)
        uni.setStorageSync('course_completions', completions)
        
        // 更新统计数据
        this.updateStats()
      } catch (e) {
        console.error('记录完成状态失败:', e)
      }
    },
    
    updateStats() {
      try {
        let stats = uni.getStorageSync('user_stats') || {}
        stats.meditationCount = (stats.meditationCount || 0) + 1
        stats.totalMeditationTime = (stats.totalMeditationTime || 0) + this.duration
        uni.setStorageSync('user_stats', stats)
      } catch (e) {
        console.error('更新统计数据失败:', e)
      }
    }
  }
}
</script>

<style scoped>
.meditation-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding-bottom: 200rpx;
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

/* 课程列表 */
.course-list {
  padding: 30rpx;
}

.course-item {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.course-cover {
  position: relative;
  height: 300rpx;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-icon {
  font-size: 60rpx;
  color: white;
}

.course-info {
  padding: 30rpx;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.course-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  flex: 1;
  margin-right: 20rpx;
}

.course-duration {
  background: var(--accent-color);
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.duration-text {
  font-size: 24rpx;
  color: var(--primary-color);
  font-weight: 600;
}

.course-desc {
  font-size: 28rpx;
  color: var(--text-secondary);
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.course-meta {
  display: flex;
  gap: 30rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.meta-icon {
  font-size: 24rpx;
}

.meta-text {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

/* 播放器 */
.player-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 2rpx solid var(--border-color);
  padding: 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.player-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.player-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.player-text {
  flex: 1;
}

.player-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 5rpx;
}

.player-progress {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.player-controls {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.control-btn {
  font-size: 36rpx;
  padding: 10rpx;
}

.play-btn {
  font-size: 48rpx;
  color: var(--primary-color);
}

.progress-bar {
  width: 100%;
}

.progress-track {
  height: 6rpx;
  background: var(--border-color);
  border-radius: 3rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  transition: width 0.3s ease;
}
</style>